#include <iostream>
#include <queue>
#include <pthread.h>
using namespace std;
template <class T>
class blockqueue
{
public:
    blockqueue(int maxcapacity = 5)
        : _capacity(maxcapacity)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_pcond, nullptr);
        pthread_cond_init(&_ccond, nullptr);
    }
    ~blockqueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_pcond);
        pthread_cond_destroy(&_ccond);
    }

    void push(const T &data)
    {
        pthread_mutex_lock(&_mutex);
        while (is_full())
        {
            pthread_cond_wait(&_pcond, &_mutex);
        }
        _q.push(data);
        pthread_cond_signal(&_ccond);
        pthread_mutex_unlock(&_mutex);
    }
    void pop(T *data)
    {
        pthread_mutex_lock(&_mutex);
        while (is_empty())
        {
            pthread_cond_wait(&_ccond, &_mutex);
        }
        *data = _q.front();
        _q.pop();
        pthread_cond_signal(&_pcond);
        pthread_mutex_unlock(&_mutex);
    }
    bool is_full()
    {
        return _q.size() == _capacity;
    }
    bool is_empty()
    {
        return _q.size() == 0;
    }

public:
    queue<T> _q;            // 阻塞队列
    pthread_mutex_t _mutex; // 互斥锁
    pthread_cond_t _pcond;  // 生产者条件变量
    pthread_cond_t _ccond;  // 消费者条件变量
    int _capacity;          // 缓冲区容量
};